package cn.wit.test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.jni.Buffer;

public class AccessLog extends HttpServlet{
		
		private BufferedWriter bw;
		
		private DateFormat Format;
	
		@Override
		public void init() throws ServletException {
			
			//获取单个类得初始化参数
//			ServletConfig config = getServletConfig();
//			
//			String logFile = config.getInitParameter("logFile");
//			
//			String dateFormat = config.getInitParameter("dateFormat");
			
			//获取全局初始化参数
			ServletContext context = getServletContext();
			
			String logFile = context.getInitParameter("logFile");
			
			String dateFormat = context.getInitParameter("dateFormat");
			
			try {
				bw = new BufferedWriter(new FileWriter(logFile,true));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Format = new SimpleDateFormat(dateFormat);
		}
		

		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			
			ServletContext context = getServletContext();
			
			System.out.println(context.getAttribute("count"));
			
			Date date = new Date();
			
			System.out.println(req.getRemoteAddr());
			
			System.out.println("有人访问"+date);
			
			String content = req.getRemoteAddr() + "\t" +Format.format(date);
			
			logFile(content);
		}
		
		public synchronized void logFile(String content) {
			
			try{
				
				bw.write(content);
				
				bw.write("\r\n");
				
				bw.flush();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		@Override
		public void destroy() {
		// TODO Auto-generated method stub
			try {
				
				if(bw != null) {
					bw.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
